<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span> 总记录数:{{ total }}条 </span>
        </template>
        <template #right>
          <el-button v-allow="'import_excel'" type="warning">导入excel</el-button>
          <el-button v-allow="'export_excel'" type="danger" @click="exportToExcel">导出excel</el-button>
          <el-button
            v-allow="'add'"
            type="primary"
            @click="showDialog = true"
          >新增员工</el-button>
        </template>
      </page-tools>
      <el-card style="margin-top: 10px">
        <!-- sortable 表格排序  default-sort="{prop:'workNumber', order:'descending'}"默认排序: 对工号降序 -->
        <el-table
          border
          :data="list"
          :default-sort="{ prop: 'timeOfEntry', order: 'descending' }"
        >
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="头像">
            <template #default="{row}">
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="width:100%"
                @click="showCode(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable />
          <el-table-column label="聘用形式">
            <template #default="{ row }">
              {{ formatHireType(row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <!-- 方式一 查询参数传参 -->
              <!-- <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button> -->
              <!-- 方式二: 路径参数传参 -->
              <el-button type="text" size="small" @click="$router.push(`/employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hAssign(row.id)">分配角色</el-button>
              <el-button
                type="text"
                size="small"
                @click="hDel(row.id)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            :current-page="page"
            :page-sizes="[2, 5, 10, 20]"
            :page-size="size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <!-- 新增员工弹层 -->
      <el-dialog title="新增员工" :visible.sync="showDialog" @close="hClose">
        <addOrEdit ref="myEmp" @success="hSuccess" />
      </el-dialog>
      <!-- 分配角色弹层 -->
      <el-dialog title="分配角色" :visible.sync="assignShowDialog">
        <assignRole v-if="assignShowDialog" :user-id="userId" @success="assignShowDialog=false" />
      </el-dialog>

      <!-- 显示二维码 -->
      <el-dialog title="二维码" :visible.sync="showCodeDialog">
        <el-row type="flex" justify="center">
          <canvas ref="myCanvas" />
        </el-row>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import addOrEdit from './empDialog.vue'
import { getEmployeeList, delEmployee } from '@/api/employees'
import employeesEnum from '@/constant/employees'
import assignRole from './assignRole.vue'
import qrCode from 'qrcode'
// [{id: 1, value: '正式'},{id: 2, value: '非正式'}] ---> {1:正式, 2:非正式}
// 将枚举中的数据遍历转换中 key和value的对象
// const hireType = {}
// employeesEnum.hireType.forEach(item => {
//   hireType[item.id] = item.value
// })
// 方法3: 数组的reduce方法
const hireType = employeesEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  name: 'EmployeesPage',
  components: {
    addOrEdit,
    assignRole
  },
  data() {
    return {
      list: [],
      page: 1,
      size: 5,
      total: 0,
      showDialog: false, // 新增员工弹层
      assignShowDialog: false, // 角色弹层
      userId: '',
      showCodeDialog: false
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 生成二维码
    showCode(url) {
      this.showCodeDialog = true
      if (url) {
        // dom是异步更新的 dialog是在点击时才弹出生成的  所以一开始获取不到 会undefined
        this.$nextTick(() => {
          // qrCode.toCanvas(dom, info)
          qrCode.toCanvas(this.$refs.myCanvas, url)
        })
      }
    },
    hAssign(id) {
      this.userId = id
      this.assignShowDialog = true
    },
    // 删除
    hDel(id) {
      this.$confirm('你确定要删除该员工吗?')
        .then(async() => {
          const res = await delEmployee(id)
          if (this.list.length === 1) {
            this.page--
            if (this.page <= 0) {
              this.page = 1
            }
          }
          if (res.data.code === 10000) {
            this.loadEmployeeList()
          }
        })
        .catch((error) => console.log(error))
    },
    // 关闭弹层
    hClose() {
      this.$refs.myEmp.resetForm()
    },
    // 子传父 关弹层和刷新页面
    hSuccess() {
      this.total++
      const maxPage = Math.ceil(this.total / this.size)
      // 将当前页码值切换到最后一页
      this.page = maxPage
      // 关弹层 刷新页面
      this.showDialog = false
      this.loadEmployeeList()
    },
    // 使用枚举数据格式化聘用形式的数据
    formatHireType(value) {
      // console.log(value)
      // value的值有可能是1 || 2
      // const obj = employeesEnum.hireType.find(item => item.id === value)
      // return obj ? obj.value : '未知'
      // // 格式化方式2: 直接从转换的对象中根据键取值
      return hireType[value] || '未知'
    },
    // 处理每页显示多少条的变化
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.page = 1
      this.size = val
      this.loadEmployeeList()
    },
    // 处理当前页码的变化
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.page = val
      this.loadEmployeeList()
    },
    // 加载员工列表
    async loadEmployeeList() {
      const res = await getEmployeeList(this.page, this.size)
      // console.log(res, 'res')
      this.list = res.data.data.rows
      this.total = res.data.data.total
    },
    // 导出至excel格式
    exportToExcel() {
      const { tHeader, result } = this.formatToExcel(this.list)
      console.log(tHeader, 'tHeader')
      console.log(result, 'result')
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader,
          data: result,
          filename: '', // 设置文件名称
          autowidth: true, // 宽度自适应
          bookType: 'xlsx' // 导出的文件类型 xlsx
        })
      })
    },
    // 格式化成excel格式
    formatToExcel(list) {
      //    中引文的映射对象
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      // tHeader = ['编号','密码','手机号','姓名','入职日期',.......]
      // 1 生成表头
      // tHeader  ---> ['转正日期', '部门', '聘用形式', '编号', '手机号', '密码', '头像地址', '入职日期', '姓名', '工号']
      const one = list[0]
      if (!one) return
      const tHeader = Object.keys(one).map(en_key => {
        return mapInfo[en_key]
      })
      // 2 生成表的内容data
      const result = list.map(item => {
        return Object.values(item)
      })
      return { tHeader, result }
    }
  }
}
</script>

<style>
</style>
